package com.learn.threadpool;

import com.learn.constant.MathConstant;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * NewCachedThreadPool
 *
 * 无界线程池，可以进行自动线程回收
 * 创建一个可缓存线程池，如果线程池长度超过处理需要，可灵活回收空闲线程，若无可回收，则新建线程
 */
public class NewCachedThreadPoolTest {

    public static void main(String[] args) {

        testRunnable();

        testCallable();

    }

    /**
     * 执行Runnable任务
     */
    private static void testRunnable(){

        ExecutorService service = Executors.newCachedThreadPool();

        for(int i = MathConstant.INT_ZERO; i < MathConstant.INT_100; i ++) {
            service.execute(new MyThread(i));
        }

        service.shutdown();
    }

    /**
     * 执行Callable任务
     */
    private static void testCallable(){

        ExecutorService service = Executors.newCachedThreadPool();

        List<Future<String>> resultList = new ArrayList<>();

        for(int i = MathConstant.INT_ZERO; i < MathConstant.INT_100; i ++) {
            Future<String> future = service.submit(new MyThread2(i));
            resultList.add(future);
        }

        //遍历任务的结果
        for (Future<String> fs : resultList){
            try{
                while(!fs.isDone()){
                    System.out.println(fs.get());
                }
            }catch(InterruptedException | ExecutionException e){
                e.printStackTrace();
            } finally{
                //启动一次顺序关闭，执行以前提交的任务，但不接受新任务
                service.shutdown();
            }
        }
    }
}
